package com.kieoo.user.filter;

import com.kieoo.user.utils.TokenUtils;
import com.kieoo.user.utils.UserUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;

@Component
public class TokenFilter implements Filter, Ordered {
    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 获取请求uri
        String uri = request.getRequestURI();
        //获取请求方式
        String method = request.getMethod();
        // 处理CORS跨域的OPTIONS请求以及注册，登录请求直接放行
        if("OPTIONS".equals(method) || uri.contains("/login/") || uri.contains("/register/")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            // 获取token
            String jwtToken = request.getHeader("Authorization");
            // 从token中获取userId
            String userId = TokenUtils.getLoginUserId(jwtToken);
            // 将userId设置到线程本次存储中
            UserUtils.setUserId(userId);
            // 过滤器放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
